package com.dns.customers.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.dns.customers.AppPage;
import com.dns.customers.DnsTask;
import com.dns.customers.dao.CustomerDao;
import com.dns.customers.dao.DomainDao;
import com.dns.customers.model.*;
import com.dns.customers.model.dnsres.Area;
import com.dns.customers.model.dnsres.QueryTask;
import com.dns.customers.model.dnsres.Record;
import com.dns.customers.model.dnsres.Res;
import com.dns.customers.service.DomainService;
import com.dns.framework.data.IDataset;
import com.dns.framework.page.Pagination;
import com.util.JsonUtils;
import com.util.SSLUtils;
import com.util.XlsMain;
import jdk.nashorn.internal.runtime.Debug;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.ArrayUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.transaction.support.DefaultTransactionDefinition;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.util.DataSourceUtil.getOrderId;

/**
 * 域名服务接口
 *
 * @author :  yulei
 * @data :  2018/5/28 18:13
 * @Version :  1.0
 **/

@Service
@Transactional(propagation=Propagation.REQUIRED, rollbackFor=Exception.class)
public class DomainServiceImpl extends AppPage implements DomainService {


    @Autowired
    DomainDao domainDao;
    @Autowired
    CustomerDao customerDao;

    @Autowired
    private DataSourceTransactionManager transactionManager;

    static {
        //忽略SSL认证
        try {
            SSLUtils.ignoreSsl();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 新增或修改域名信息
     * @param req
     * @return
     */
    public String  addCustDomain(HttpServletRequest req){
        JSONObject resultJson = new JSONObject();
        JSONObject message = new JSONObject();
        try {
            //从请求中取出参数
            InputStream is =req.getInputStream();
            String contentStr = IOUtils.toString(is, "utf-8");
            log.debug("contentStr: "+contentStr);

            //解析参数
            //将前台传递的参数转换成json
            JSONObject  requestInfo= JSONObject.fromObject(contentStr);
            //取出大客户id
            String custId=requestInfo.getString("custId");
            User user =buildUserObject(custId);
            //取出域名集合
            JSONArray jsonArray = requestInfo.getJSONArray("domainInfo");
            List<Map<String,Object>> rootDomains = new ArrayList<>();
            Map<String,List<Map<String,Object>>> childDomainMap = new HashMap<>();
            Map<String,List<String>> deleteTypes = new HashMap<>();
            for(int i=0;i<jsonArray.size();i++){
                JSONObject domain = jsonArray.getJSONObject(i);
                String domainName = (String)domain.get("domainName");
                String type = domain.getString("domain_type");
                if (type == null){
                    continue;
                }
                Map<String,Object> domainMap = new HashMap<>();
                domainMap.put("domainName",domainName);
                JSONArray types = domain.getJSONArray("type");
                if (types == null){
                    message.put("errorCode", "8888");
                    message.put("errorMsg","域名："+domainName+" 没有选择解析类型");
                    resultJson.put("result", message);
                    return resultJson.toString();
                }
                List<Map<String,Object>> ll = domainDao.checkDeleteTypes(domainName,type,(List<String>) domain.get("type"));
                if (ll != null ){
                    for (Map<String,Object> mm : ll){
                        String t = (String)mm.get("type");
                        List l = deleteTypes.get(domainName+type);
                        if (l == null)
                            l=new ArrayList();
                        l.add(t);
                        deleteTypes.put(domainName+type,l);
                    }
                }
                domainMap.put("type",types);
                domainMap.put("domain_type",domain.get("domain_type"));
                domainMap.put("remark",domain.get("remark"));

                //如果是0，代表是根域名
                if ("0".equals(type)){
                    domainMap.put("parent_domain","");
                    rootDomains.add(domainMap);
                }else {//子域名
                    domainMap.put("parent_domain",domain.get("parent_domain"));
                    List<Map<String,Object>> childDomains = childDomainMap.get(domain.get("parent_domain"));
                    if (childDomains == null){
                        childDomains = new ArrayList<>();
                    }
                    childDomains.add(domainMap);
                    childDomainMap.put((String)domain.get("parent_domain"),childDomains);
                }
            }
            if (rootDomains.size()>0){
                try{
                    String dbresult = custRootDomain(user,rootDomains);
                    if (dbresult.contains("成功")){
                        //删除字符串根
                        StringBuffer deleteRootStr = new StringBuffer();
                        deleteRootStr.setLength(0);
                        deleteRootStr.append("{\"custId\":\""+custId+"\",\"domains\":[");
                        int a = 0;
                        for (Map<String,Object> domain : rootDomains){
                            String name = (String)domain.get("domainName");
                            Object dtype = domain.get("domain_type");
                            List<String> types =deleteTypes.get(name+dtype);
                            if (types==null){
                                continue;
                            }
                            if (a > 0){
                                deleteRootStr.append(",");
                            }
                            deleteRootStr.append("{\"domainName\":\""+name+"\",\"domainType\":\""+dtype+"\"");
                            deleteRootStr.append(",\"type\":[");
                            int b=0;
                            for (String tt : types){
                                if(b>0){
                                    deleteRootStr.append(",");
                                }
                                deleteRootStr.append("\""+tt+"\"");
                                b++;
                            }
                            deleteRootStr.append("]}");
                            a++;
                        }
                        deleteRootStr.append("]}");
                        System.out.println("deleteRootStr:"+deleteRootStr.toString());
                        delDomainRecordList(deleteRootStr.toString());
                        message.put("errorMsg","根域名修改成功");
                    }else{
                        message.put("errorMsg",dbresult);
                        message.put("errorCode",dbresult);
                    }
                }catch (Exception e){
                    message.put("errorCode", "8888");
                    message.put("errorMsg","根域名修改异常 ");
                    resultJson.put("result", message);
                    e.printStackTrace();
                    //                    return resultJson.toString();
                }
            }
            if (childDomainMap.size()>0){
                String messa = message.get("errorMsg")==null?"":(String)message.get("errorMsg");
                try{
                    String dbresult = custchildDomain(user,childDomainMap);
                    if (dbresult.contains("成功")){
                        //删除字符串zi
                        StringBuffer deleteChildStr = new StringBuffer();
                        deleteChildStr.setLength(0);
                        deleteChildStr.append("{\"custId\":\""+custId+"\",\"domains\":[");
                        int a = 0;
                        for (Map.Entry<String,List<Map<String,Object>>> entry : childDomainMap.entrySet()){
                            List<Map<String,Object>> childlist = entry.getValue();
                            if (childlist != null){
                                for (Map<String,Object> domain : childlist){
                                    String name = (String)domain.get("domainName");
                                    Object dtype = domain.get("domain_type");
                                    List<String> types =deleteTypes.get(name+dtype);
                                    if (types==null){
                                        continue;
                                    }
                                    if (a > 0){
                                        deleteChildStr.append(",");
                                    }
                                    deleteChildStr.append("{\"domainName\":\""+name+"\",\"domainType\":\""+dtype+"\"");
                                    deleteChildStr.append(",\"type\":[");
                                    int b=0;
                                    for (String tt : types){
                                        if(b>0){
                                            deleteChildStr.append(",");
                                        }
                                        deleteChildStr.append("\""+tt+"\"");
                                        b++;
                                    }
                                    deleteChildStr.append("]}");
                                    a++;
                                }
                            }
                        }
                        deleteChildStr.append("]}");
                        System.out.println("deleteChildStr:"+deleteChildStr);
                        delDomainRecordList(deleteChildStr.toString());
                        messa += " 子域名添加成功";
                        message.put("errorMsg",messa);
                        resultJson.put("result", message);
                    }else{
                        message.put("errorMsg",messa+","+dbresult);
                        message.put("errorCode",messa+"子域名添加异常");
                        resultJson.put("result", message);
                    }
                }catch (Exception e){
                    message.put("errorCode", "8888");
                    message.put("errorMsg",messa += " 子域名保存异常");
                    resultJson.put("result", message);
                    e.printStackTrace();
                    return resultJson.toString();
                }
            }
            resultJson.put("result", message);
        }catch (Exception e){
            message.put("errorCode", e);
            message.put("errorMsg","添加异常");
            resultJson.put("result", message);
            e.printStackTrace();
            return resultJson.toString();
        }
        return  resultJson.toString();
    }
    //新增或修改根域名
    public String custRootDomain(User user,List<Map<String,Object>> rootDomains) throws Exception{
        String sult = "";
        //自定义事务，手动提交事务
        DefaultTransactionDefinition def = new DefaultTransactionDefinition();
        def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);// 事物隔离级别，开启新事务
        TransactionStatus status = transactionManager.getTransaction(def); // 获得事务状态
        try{
            //调用数据库
            sult = domainDao.custDomain(user.getName(),rootDomains);
            if(sult.contains("成功")){
                //调用润通接口
                //拼接润通参数字符串
                StringBuffer str = new StringBuffer();
                str.append("{\"customers\":{");
                str.append("\"user\":{\"name\":\""+user.getName()+"\",\"password\":\""+user.getPassword()+"\",\"accessIp\":\""+user.getAccessIp()+"\"},");
                str.append("\"customerDomain\":{");
                str.append("\"rootDomain\":[");
                StringBuffer ss = new StringBuffer();
                for (Map<String,Object> domain : rootDomains){
                    if (ss.length()>0){
                        ss.append(",");
                    }
                    ss.append("{\"domainName\":\""+domain.get("domainName")+"\"");
                    ss.append(",\"record\":[");
                    StringBuffer typeStr = new StringBuffer();
                    for (String type : (List<String>)domain.get("type")){
                        if (typeStr.length()>0){
                            typeStr.append(",");
                        }
                        typeStr.append("{\"type\":\""+type+"\"}");
                    }
                    ss.append(typeStr+"]}");
                }
                str.append(ss+"]}}}");
                log.debug(" custRootDomain:"+str.toString());

                //***将JSON字符串转换为XML字符串***
                JSONObject customers = JSONObject.fromObject(str.toString());
                JSONObject custJson = JsonUtils.jsonFilterNull(customers);
                JSONObject responseJson =invokeRTWebService(custJson,MODIFY_CUSTOMER_ROOT_RECORD);
                JSONObject results = (JSONObject) responseJson.get("results");
                JSONArray result = (JSONArray) results.get("result");

                //只返回一个ressult节点，只取第一个节点即可
                JSONObject resultJson = result.getJSONObject(0);

                //有returncode表示业务办理失败
                if (resultJson.containsKey("returncode")) {

                    sult = "润通接口保存失败！";
                    transactionManager.rollback(status);
                }else{
                    sult = "保存成功！";
                    transactionManager.commit(status);
                }
            }

        }catch (Exception e){
            transactionManager.rollback(status);
            throw e;
        }
        return sult;
    }
    //新增或修改子域名
    public String custchildDomain(User user,Map<String,List<Map<String,Object>>> childDomainMap) throws Exception{
        String sult = "";
        //自定义事务，手动提交事务
        DefaultTransactionDefinition def = new DefaultTransactionDefinition();
        def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);// 事物隔离级别，开启新事务
        TransactionStatus status = transactionManager.getTransaction(def); // 获得事务状态
        try{
            //调用数据库
            domainDao.custChildDomain(user.getName(),childDomainMap);

            //调用润通接口
            //拼接润通参数字符串
            StringBuffer str = new StringBuffer();
            str.append("{\"customers\":{");
            str.append("\"user\":{\"name\":\""+user.getName()+"\",\"password\":\""+user.getPassword()+"\",\"accessIp\":\""+user.getAccessIp()+"\"},");
            str.append("\"customerDomain\":{");
            str.append("\"rootDomain\":[");
            StringBuffer ss = new StringBuffer();
            for (Map.Entry<String,List<Map<String,Object>>> domainEntry : childDomainMap.entrySet()){
                String key = domainEntry.getKey();
                List<Map<String,Object>> domains = domainEntry.getValue();
                if (ss.length()>0){
                    ss.append(",");
                }
                ss.append("{\"domainName\":\""+key+"\",");
                ss.append("\"childDomain\":[");
                StringBuffer childDomain = new StringBuffer();
                for (Map<String,Object> domain : domains){
                    if (childDomain.length()>0){
                        childDomain.append(",");
                    }
                    childDomain.append("{\"name\":\""+domain.get("domainName")+"\",");
                    childDomain.append("\"record\":[");
                    StringBuffer typeStr = new StringBuffer();
                    for (String type : (List<String>)domain.get("type")){
                        if (typeStr.length()>0){
                            typeStr.append(",");
                        }
                        typeStr.append("{\"type\":\""+type+"\"}");
                    }
                    childDomain.append(typeStr+"]}");
                }
                ss.append(childDomain+"]}");

            }

            str.append(ss+"]}}}");
            log.debug(" custRootDomain:"+str.toString());

            //***将JSON字符串转换为XML字符串***
            JSONObject customers = JSONObject.fromObject(str.toString());
            JSONObject custJson = JsonUtils.jsonFilterNull(customers);
            JSONObject responseJson =invokeRTWebService(custJson,ADD_CUSTOMER_CONFIG);
            JSONObject results = (JSONObject) responseJson.get("results");
            JSONArray result = (JSONArray) results.get("result");

            //只返回一个ressult节点，只取第一个节点即可
            JSONObject resultJson = result.getJSONObject(0);

            //有returncode表示业务办理失败
            if (resultJson.containsKey("returncode")) {
                sult = "润通接口保存失败！";
                transactionManager.rollback(status);
            }else{
                sult = "保存成功！";
                transactionManager.commit(status);
            }

        }catch (Exception e){
            transactionManager.rollback(status);
            throw e;
        }
        return sult;
    }
    /**
     * 批量删除域名解析记录信息
     * @param
     * @return
     */
    public String delDomainRecordList(String contentStr){
        //返回前台的JSON串
        JSONObject resultJSON = new JSONObject();
        JSONObject message = new JSONObject();
        try{
            //解析参数
            //将前台传递的参数转换成json
            JSONObject  requestInfo= JSONObject.fromObject(contentStr);
            JSONArray domains = requestInfo.getJSONArray("domains");
            if (domains == null || domains.size()<1){
                message.put("errorMsg","参数异常");
                message.put("errorCode","参数异常");
                resultJSON.put("result",message);
                return resultJSON.toString();
            }
            String custId = requestInfo.getString("custId");
            if(custId == null || "".equals(custId)){
                message.put("errorMsg","没有用户信息");
                message.put("errorCode","没有用户信息");
                resultJSON.put("result",message);
                return resultJSON.toString();
            }
            User user = null;
            try{
                user = buildUserObject(custId);
            }catch (Exception e){
                message.put("errorMsg","没有查询到用户信息");
                message.put("errorCode","没有查询到用户信息");
                resultJSON.put("result",message);
                return resultJSON.toString();
            }
            //拼接成润通接口需要的数据样式
            StringBuffer rootDomainStr = new StringBuffer();
            rootDomainStr.append("{\"customers\":{\"user\":{\"name\":\""+user.getName()+"\"," +
                    "\"password\":\""+user.getPassword()+"\",\"accessIp\":\""+getAccess_ip()+"\"}," +
                    "\"customerDomain\":{\"rootDomain\":[");
            StringBuffer childDomainStr = new StringBuffer();
            childDomainStr.append("{\"customers\":{\"user\":{\"name\":\""+user.getName()+"\"," +
                    "\"password\":\""+user.getPassword()+"\",\"accessIp\":\""+getAccess_ip()+"\"}," +
                    "\"customerDomain\":{\"delDomain\":[");
            int root=0,child=0;
            for (int i=0;i<domains.size();i++){
                JSONObject domain = domains.getJSONObject(i);
                String domainName = domain.getString("domainName");
                String domainType = domain.getString("domainType");
                if (domainName == null)continue;
                if ("0".equals(domainType)){
                    if (root>0){
                        rootDomainStr.append(",");
                    }
                    rootDomainStr.append("{\"domainName\":\""+domainName+"\"," +
                            "\"domainType\":\""+domainType+"\"" );
                    List<String> types = (List<String>)domain.get("type");
                    if (types == null){
                        types =domainDao.checkDomainTypes(domainName,domainType);
                    }
                    if (types == null || types.size() <=0){
                        continue;
                    }
                    rootDomainStr.append(",\"record\":[");
                    int l=0;
                    for (int k = 0;k < types.size();k++){
                        if (l>0){
                            rootDomainStr.append(",");
                        }
                        rootDomainStr.append("{\"type\":\""+types.get(k)+"\"}");
                        l++;
                    }
                    rootDomainStr.append("]");
                    rootDomainStr.append("}");
                    root++;
                }else {
                    if (child>0){
                        childDomainStr.append(",");
                    }
                    childDomainStr.append("{\"domainName\":\""+domain.get("domainName")+"\"," +
                            "\"domainType\":\""+domain.get("domainType")+"\"");
                    List<String> types = (List<String>)domain.get("type");
                    if (types != null){
                        childDomainStr.append(",\"record\":[");

                        int l=0;
                        for (int k = 0;k < types.size();k++){
                            if (l>0){
                                childDomainStr.append(",");
                            }
                            childDomainStr.append("{\"type\":\""+types.get(k)+"\"}");
                            l++;
                        }
                        childDomainStr.append("]");
                    }
                    childDomainStr.append("}");
                    child++;
                }
            }
            childDomainStr.append("]}}}");
            rootDomainStr.append("]}}}");
            log.debug("childDomainStr:"+childDomainStr);
            log.debug("rootDomainStr:"+rootDomainStr);
            StringBuffer msge = new StringBuffer();
            StringBuffer msgeCode = new StringBuffer();
            if (root > 0){
                //自定义事务，手动提交事务
                DefaultTransactionDefinition def = new DefaultTransactionDefinition();
                def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);// 事物隔离级别，开启新事务
                TransactionStatus status = transactionManager.getTransaction(def); // 获得事务状态
                //数据库删除数据
                String msg = domainDao.delDomainRecordList(rootDomainStr.toString());
                if(msg.contains("成功")){
                    JSONObject customers = JSONObject.fromObject(rootDomainStr.toString());
                    //***将前台传递的JSON字符串转换为XML字符串***
                    JSONObject queryDnsResultJson = JsonUtils.jsonFilterNull(customers);
                    //**************调用润通接口START**************************
                    JSONObject resulJSON=invokeRTWebService(queryDnsResultJson,DEL_CUSTOMER_ROOT_RECORD);
                    //**************调用润通接口END***************************

                    //获取客户域名信息
                    JSONObject results= (JSONObject) resulJSON.get("results");
                    //result节点信息处理
                    JSONArray result = results.getJSONArray("result");
                    JSONObject messageInfo=result.getJSONObject(0);
                    //有returncode表示业务办理失败
                    if (messageInfo.containsKey("returncode")) {
                        msge.append(messageInfo.get("errorMsg"));
                        msgeCode.append(messageInfo.get("errorMsg"));
                        //数据库事务回滚
                        if (((String)messageInfo.get("errorMsg")).contains("部分域名不存在")){
                            transactionManager.commit(status);
                        }else {
                            transactionManager.rollback(status);
                        }
                    }else{
                        msge.append("根域名解析记录删除成功 ");
                        transactionManager.commit(status);
                    }
                }else{
                    msge.append("根域名解析记录删除失败 ");
                    msgeCode.append("根域名解析记录删除失败 ");
                    //数据库事务回滚
                    transactionManager.rollback(status);
                }
            }
            //子域名删除
            if (child > 0){
                //自定义事务，手动提交事务
                DefaultTransactionDefinition def = new DefaultTransactionDefinition();
                def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);// 事物隔离级别，开启新事务
                TransactionStatus status = transactionManager.getTransaction(def); // 获得事务状态
                //数据库删除数据
                String msg = domainDao.delCustomerConfig(childDomainStr.toString());
                if(msg.contains("成功")){
                    JSONObject customers = JSONObject.fromObject(childDomainStr.toString());
                    //***将前台传递的JSON字符串转换为XML字符串***
                    JSONObject queryDnsResultJson = JsonUtils.jsonFilterNull(customers);
                    //**************调用润通接口START**************************
                    JSONObject resulJSON=invokeRTWebService(queryDnsResultJson,DEL_CUSTOMER_CONFIG);
                    //**************调用润通接口END***************************

                    //获取客户域名信息
                    JSONObject results= (JSONObject) resulJSON.get("results");
                    //result节点信息处理
                    JSONArray result = results.getJSONArray("result");
                    JSONObject messageInfo=result.getJSONObject(0);
                    //有returncode表示业务办理失败
                    if (messageInfo.containsKey("returncode")) {
                        msge.append(messageInfo.get("errorMsg"));
                        msgeCode.append(messageInfo.get("errorMsg"));
                        //数据库事务回滚
                        if (((String)messageInfo.get("errorMsg")).contains("不存在")){
                            transactionManager.commit(status);
                        }else{
                            transactionManager.rollback(status);
                        }
                    }else{
                        msge.append("子域名解析记录删除成功 ");
                        transactionManager.commit(status);
                    }
                }else{
                    msge.append("子域名解析记录删除失败 ");
                    msgeCode.append("子域名解析记录删除失败 ");
                    //数据库事务回滚
                    transactionManager.rollback(status);
                }
            }
            if (msge.length() <= 0){
                msge.append("删除成功");
            }
            message.put("errorMsg",msge.toString());
            if (msgeCode.length() > 0){
                message.put("errorCode",msge.toString());
            }
            resultJSON.put("result",message);
        }catch(Exception e){
            message.put("errorMsg","域名解析记录删除异常");
            message.put("errorCode","域名解析记录删除异常");
            resultJSON.put("result",message);
            e.printStackTrace();
        }
        return resultJSON.toString();
    }
    /**
     * 查询订单返回结果
     * @param request
     * @return
     */
    @Override
    public String queryOrderDetail(HttpServletRequest request) {
        JSONObject resultJson = new JSONObject();
        JSONObject message = new JSONObject();
        try {
            String orderId=request.getParameter("ORDER_ID");
            String taskType=request.getParameter("TASK_TYPE");
            Map param = new HashMap();
            param.put("ORDER_ID",orderId);
            param.put("TASK_TYPE",taskType);
            //当前页
            int currPage = Integer.parseInt(request.getParameter("CURRENT_PAGE_NUMBER"));
            //每页显示的记录数
            int pageSize = Integer.parseInt(request.getParameter("PAGE_SIZE"));
            //记录总数
            int rowCount = Integer.parseInt(request.getParameter("ROW_COUNT"));
            //分页工具类
            Pagination pagination = new Pagination();
            pagination.setCurrPage(currPage);
            pagination.setPageSize(pageSize);
            pagination.setRowCount(rowCount);
            //分页查询订单结果
            IDataset dataset =domainDao.getOrderDatilPage(param,pagination);
            List<Map<String, Object>> proList=dataset.getResultList();
            if (proList == null){
                proList = new ArrayList<>();
            }
            int rowCounts = dataset.getCount();
            pagination.setRowCount(rowCounts);
            message.put("reusultcode", "0000");
            message.put("message", "查询订单信息成功");
            //将结果信息存放起来
            message.put("ORDER_DETAILS", proList);
            message.put("ORDER_DETAIL_COUNT", countOrderDetails(orderId));
            resultJson.put("result", message);
            resultJson.put("ROW_COUNT", rowCounts);//记录总数
            resultJson.put("PAGE_COUNT", pagination.getPageCount());//总页数
        }catch (Exception e){
            log.error("查询订单详情异常:",e);
            message.put("reusultcode", "8888");
            message.put("message", e.getMessage());
            resultJson.put("result", message);
        }
        return resultJson.toString();
    }
    //对域名解析结果做一个统计
    public JSONObject countOrderDetails(String orderId) throws Exception{
        JSONObject obj = new JSONObject();
        Map<String,Object> orderMap = domainDao.queryOrderById(orderId);
        String areacodes = orderMap.get("AREA_CODE")+"";

        //获取所有省份信息
        Map param = new HashMap();
        param.put("VALIDFLAG","0"); //0 表示有效
        param.put("AREA_LEVEL","1");

        List<Map<String,Object>> areaList = customerDao.getAllProvinces(param);
        Map<String,String> provinceMap = new HashMap<>();
        for (Map<String,Object> province : areaList){
            String code = (String)province.get("value");
            String name = (String)province.get("label");
            provinceMap.put(code,name);
        }
        String ragular = "\\d+\\.\\d+\\.\\d+\\.\\d+";
        int haveRes=0,noRes=0,haveProvince=0,noProvince = 0,AllRes=0;
        //获取订单解析结果集
        List<Map<String,Object>> details = domainDao.queryOrderDetailList(orderId);
        Map<String,List<Map<String,Object>>> detailMap = new HashMap<>();
        if (details != null ){
            for (Map<String,Object> detail : details){
                String proCode = (String)detail.get("PROVINCE_CODE");
                List<Map<String,Object>> l = detailMap.get(proCode);
                if (l == null){
                    l = new ArrayList<>();
                }
                l.add(detail);
                detailMap.put(proCode,l);
                //统计Res
                String res = (String)detail.get("RES");
                if (res==null || "".equals(res)){
                    noRes++;
                }else{
                    if (res.split(";")[0].matches(ragular)){
                        haveRes++;
                    }else{
                        noRes++;
                    }
                }
            }
        }
        haveProvince = detailMap.size();
        String  haveProList = "";
        for (Map.Entry<String, List<Map<String, Object>>> entry : detailMap.entrySet()){
            String key = entry.getKey();
            if (!"".equals(haveProList)){
                haveProList += ", ";
            }
            haveProList += provinceMap.get(key);
        }
        int allpronum = 0;
        String  noProList = "";
        if (!"null".equals(areacodes) && !"".equals(areacodes)){
            String[] ss = areacodes.split(";");
            allpronum = ss.length;
            a:for (String s : ss){
                b:for (Map.Entry<String, List<Map<String, Object>>> entry : detailMap.entrySet()){
                    String key = entry.getKey();
                    if (s.equals(key)){
                       continue a;
                    }
                }
                if (!"".equals(noProList)){
                    noProList += ", ";
                }
                noProList += provinceMap.get(s);
            }
        }else {
            allpronum = provinceMap.size();
            a:for (Map.Entry<String,String> pro : provinceMap.entrySet()){
                String s = pro.getKey();
                b:for (Map.Entry<String, List<Map<String, Object>>> entry : detailMap.entrySet()){
                    String key = entry.getKey();
                    if (s.equals(key)){
                        continue a;
                    }
                }
                if (!"".equals(noProList)){
                    noProList += ", ";
                }
                noProList += pro.getValue();
            }
        }

        noProvince = allpronum-detailMap.size();
        obj.put("AllRes",haveRes+noRes);
        obj.put("haveRes",haveRes);
        obj.put("noRes",noRes);
        obj.put("haveProvince",haveProvince);
        obj.put("noProList",noProList);
        obj.put("haveProList",haveProList);
        obj.put("noProvince",noProvince);
        return obj;
    }
    /**
     * 下发订单任务,包含域名解析和缓存清除
     * 下发之前，先校验本地数据库是否有在途订单，若有在途单，则提示无法下发.
     * 如果是域名解析任务，校验当日的正式域名解析订单是否超过限制数量
     * 目的是等待定时器将上一个订单任务解析结果入到我们的订单明细表dns_order_detail
     * @param params
     * @return
     */
    public String addOrderTask(String params){
        JSONObject requestParam= JSONObject.fromObject(params);
        String task_type=requestParam.getString("TASK_TYPE");

        String result="";
        Map param = new HashMap();
        param.put("CUST_ID",requestParam.getString("custId"));
        param.put("TASK_TYPE",requestParam.getString("TASK_TYPE"));
        JSONObject resultJSON =new JSONObject();
        JSONObject message = new JSONObject();
        String domainName = requestParam.getString("domainName");
        if(domainName == null){
            message.put("errorMsg", "还没有选择域名！");
            message.put("errorCode", "8888");
            resultJSON.put("result",message);
            result=resultJSON.toString();
            return result;
        }
        param.put("DOMAIN_NAME",domainName);
        if(DnsTask.TASK_TYPE_RES.equals(task_type)){//域名解析
            //校验是否有在途单，若有在途单，则提示无法下发，等待在途单完成之后在下发.
            boolean flag= domainDao.checkHasTradeOrder(param);
            if(flag){
                message.put("errorMsg", "有在途的域名解析订单任务未完成，请稍后再试！");
                message.put("errorCode", "8888");
                resultJSON.put("result",message);
                result=resultJSON.toString();
                return result;
            }
            //校验订单下发的域名数量是否超过限制数量
            flag = domainDao.checkOrderNum(param);
            if (flag){
                message.put("errorMsg", "域名超过最大数量，无法下发任务！");
                message.put("errorCode", "8888");
                resultJSON.put("result",message);
                return resultJSON.toString();
            }
            result= addDnsResultTask(requestParam);
        }else if(DnsTask.TASK_TYPE_CLEAN.equals(task_type)){//清除缓存
            //校验订单下发的域名数量是否超过限制数量
            boolean flag = domainDao.checkOrderNum(param);
            if (flag){
                message.put("errorMsg", "缓存清除只能下发一个域名！");
                message.put("errorCode", "8888");
                resultJSON.put("result",message);
                return resultJSON.toString();
            }
            result= addCleanDomainCacheTask(requestParam);
        }
        return result;
    }
    //返回User对象
    public  User buildUserObject(String custId) throws Exception {
        User user = new User();
        user.setName(custId); //设置客户名称
        user.setAccessIp(getAccess_ip());//设置客户限制的IP
        //根据客户ID查询客户密码
        List<Map<String,Object>>  custResultList = customerDao.queryCustomerAccount(custId);
        //因客户只有一个，所有取第一个元素即可
        Map<String,Object> custResult=custResultList.get(0);
        JSONObject custResultJson= JSONObject.fromObject(custResult);
        log.debug("custResultJson: "+custResultJson);
        //客户密码
        String passsword=custResultJson.getString("CUST_PASSWORD");
        user.setPassword(passsword);
        return  user;
    }
    //下发域名解析任务
    public String addDnsResultTask(JSONObject requestJson) {
        //返回前台的JSON串
        JSONObject resultJSON = new JSONObject();
        JSONObject message = new JSONObject();
        try {
            //{ "custId":"beijingdaxue","domainName":"beida.com","areaCode":"110000;220000","type":"A","TASK_TYPE":"0"}
            //客户ID
            String custId=requestJson.getString("custId");
            //下发域名名称
            String domainName=requestJson.getString("domainName");
            //下发区域
            String areaCode=requestJson.getString("areaCode");
            //下发类型
            String type=requestJson.getString("type");
            //归属那个清除缓存任务
            String attribution =requestJson.getString("attribution");
            if("".equals(attribution)){
                attribution = null;
            }
            String orderId = getOrderId();
            //********************************
                 /*        构建对象                /
                 //********************************/
            User user = buildUserObject(custId);
            QueryDns queryDnsObject= new QueryDns();
            queryDnsObject.setUser(user);
            Query query =new Query();
            query.setWorkNum(orderId);
            Domain domain = new Domain();
            domain.setName(domainName);
            domain.setAreaCode("".equals(areaCode)?null:areaCode);
            domain.setType(type);
            query.setDomain(domain);
            queryDnsObject.setQuery(query);

            //传递
            JSONObject  addDnsResultTaskRequest =new JSONObject();
            addDnsResultTaskRequest.put("queryDns",queryDnsObject);

            JSONObject addDnsResultTaskJson = JsonUtils.jsonFilterNull(addDnsResultTaskRequest);
            //   取出JSON对象的queryDns对象
            JSONObject queryDnsJson = (JSONObject) addDnsResultTaskJson.get("queryDns");
            log.debug("queryDnsJson = " + queryDnsJson);

            /**********************************************/
            /*             下发解析任务订单                 */
            /**********************************************/

            //没有发生异常，表示数据库插入数据正常，之后调用润通接口
            String order= domainDao.addDnsResultTask(queryDnsJson.toString(),attribution);


            //**************调用润通接口START**************************
            JSONObject responseJson =invokeRTWebService(addDnsResultTaskJson,ADD_DNS_RESULT_TASK);
            JSONObject results = (JSONObject) responseJson.get("results");
            JSONArray result = (JSONArray) results.get("result");
            //只返回一个ressult节点，只取第一个节点即可
            JSONObject resultJson = result.getJSONObject(0);
            //有returncode表示业务办理失败
            if (resultJson.containsKey("returncode")) {
                String resultcode = resultJson.getString("returncode");
                message.put("errorCode", resultcode);
                message.put("errorMsg", resultJson.getString("errorMsg"));
                resultJSON.put("result", message);
                //业务办理失败，回滚事务
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return resultJSON.toString();
            }
            //**************调用润通接口END**************************
            message.put("errorMsg","下发域名解析任务成功!");
            message.put("orderId",orderId);
            resultJSON.put("result",message);;
        }catch (Exception e){
            log.error("下发DNS解析结果异常:\n", e);
            message.put("errorMsg","下发DNS解析结果异常:"+e);
            resultJSON.put("result",message);
            //数据库事务回滚
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); //第二种
        }finally {
            return resultJSON.toString();
        }
    }
    //下发清除缓存任务
    public String addCleanDomainCacheTask(JSONObject requestJson) {
        //返回前台的JSON串
        JSONObject resultJSON = new JSONObject();
        JSONObject message = new JSONObject();
        try {
            //客户ID
            String custId=requestJson.getString("custId");
            //下发域名名称
            String domainName=requestJson.getString("domainName");
            //下发区域
            String areaCode=requestJson.getString("areaCode");
            //下发类型

            //********************************
                 /*        构建对象                /
                 //********************************/
            User user = buildUserObject(custId);
            CleanCache cleanCacheObject= new CleanCache();
            cleanCacheObject.setUser(user);
            CleanTask cleanTask =new CleanTask();
            cleanTask.setDomain(domainName);
            cleanTask.setAreaCode(areaCode);
            cleanCacheObject.setCleanTask(cleanTask);

            //传递
            JSONObject  cleanCacheRequest =new JSONObject();
            cleanCacheRequest.put("cleanCache",cleanCacheObject);

            //***将前台传递的JSON字符串转换为XML字符串***
            JSONObject cleanCacheRequestJson = JsonUtils.jsonFilterNull(cleanCacheRequest);

            //将JSON 数据 转换为JavaBean
            //取出JSON对象的cleanCache对象
            JSONObject cleanCacheJson = (JSONObject) cleanCacheRequestJson.get("cleanCache");
            log.debug("cleanCacheJson = " + cleanCacheJson);
            /**********************************************/
            /*             下发域名缓存清除任务订单          */
            /**********************************************/
            //没有发生异常，表示数据库插入数据正常，之后调用润通接口
            String orderId = domainDao.addCleanDomainCacheTask(cleanCacheJson.toString());

            //**************调用润通接口START**************************
            JSONObject responseJson =invokeRTWebService(cleanCacheRequestJson,ADD_CLEAN_DOMAIN_CACHE_TASK);
            JSONObject results = (JSONObject) responseJson.get("results");
            JSONArray result = (JSONArray) results.get("result");
            //只返回一个ressult节点，只取第一个节点即可
            JSONObject resultJson = result.getJSONObject(0);

            //有returncode表示业务办理失败
            if (resultJson.containsKey("returncode")) {
                String resultcode = resultJson.getString("returncode");
                message.put("errorCode", resultcode);
                message.put("errorMsg", resultJson.getString("errorMsg"));
                resultJSON.put("result", message);
                //业务办理失败，回滚事务
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); //第二种
                return resultJSON.toString();
            }

            //**************调用润通接口END**************************

            message.put("errorMsg","下发清除域名缓存任务成功!");
            message.put("orderId",orderId);
            resultJSON.put("result",message);
        }
        catch (Exception e) {
            log.error("下发清除域名缓存任务异常:\n", e);
            message.put("errorMsg","下发清除域名缓存任务异常:"+e);
            resultJSON.put("result",message);
            //数据库事务回滚
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); //第二种
        }
        finally {
            return  resultJSON.toString();
        }
    }
    /**
     * 查询详情页的域名解析结果（缓存清除的）
     * @param custId
     * @param orderId
     * @return
     */
    @Override
    public String checkCacheTaskResult(String custId,String orderId,String domainName,String type){
        JSONObject message = new JSONObject();
        JSONObject resultJSON = new JSONObject();
        try{
            //1、查询当前要查看的有没有已经下发的订单任务，
            // 如果已经下发，直接返回记录结果，若是没有下发过任务，则下发任务
            String taskId = domainDao.checkTaskIsList(custId,orderId,domainName,type);
            if (taskId != null){
                //直接查询结果
                List<Map<String,Object>> dbList = domainDao.queryOrderDetailList(taskId);
                if (dbList == null){
                    message.put("message", "正在查询！请稍等。。。");
                    message.put("reusultcode", "正在查询！请稍等。。。");
                    resultJSON.put("result", message);
                    return resultJSON.toString();
                }
                message.put("message","查询成功");
                message.put("ORDER_DETAILS",dnsTaskResultJSON(dbList));
                message.put("ORDER_DETAIL_COUNT", countOrderDetails(taskId));
                resultJSON.put("result",message);
            }else{
                Map<String,Object> order = domainDao.queryOrderById(orderId);
                String codes = order.get("AREA_CODE")+"";
                if ("null".equals(codes))
                    codes = "";
                codes = "".equals(codes)?"":codes;
                String jsonStr = "{\"TASK_TYPE\":\"0\"," +
                        "\"domainName\":\""+domainName+"\"," +
                        "\"custId\":\""+custId+"\"," +
                        "\"type\":\""+type+"\"," +
                        "\"areaCode\":\""+codes+"\"," +
                        "\"attribution\":\""+orderId+"\"}";
                log.debug("jsonStr:"+jsonStr);
                String TaskResult = addOrderTask(jsonStr);
                if (TaskResult == null){
                    message.put("message", "查询异常");
                    message.put("reusultcode", "1111");
                    resultJSON.put("result", message);
                    return resultJSON.toString();
                }
                JSONObject resultJson = JSONObject.fromObject(TaskResult);
                if (resultJson.containsKey("errorCode")){
                    message.put("message", resultJson.getString("errorMsg"));
                    message.put("reusultcode", "1111");
                    resultJSON.put("result", message);
                    return resultJSON.toString();
                }
                message.put("message", "正在查询！请稍等。。。");
                message.put("reusultcode", "正在查询！请稍等。。。");
                resultJSON.put("result", message);
                return resultJSON.toString();
            }
        }catch (Exception e){
            log.error("查询结果异常：", e);
            message.put("message","查询结果异常");
            message.put("reusultcode","查询结果异常:"+e);
            resultJSON.put("result",message);
            //数据库事务回滚
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); //第二种
        }
        return resultJSON.toString();
    }
    //拼接返回格式
    public JSONArray dnsTaskResultJSON(List<Map<String,Object>> dbList){
        if (dbList == null){
            return null;
        }
        Map<String,List<Map<String,Object>>> mm = new HashMap<>();
        Map<String,String> code = new HashMap<>();
        Map<String,String> name = new HashMap<>();
        for (Map<String,Object> map : dbList){
            String pname = (String) map.get("PROVINCE_NAME");
            if (pname == null)
                continue;
            List<Map<String,Object>> list = mm.get(pname);
            if (list == null){
                list = new ArrayList<>();
            }
            list.add(map);
            code.put(pname,(String)map.get("PROVINCE_CODE"));
            name.put(pname,(String)map.get("PROVINCE_NAME"));
            mm.put(pname,list);
        }
        JSONArray resultList = new JSONArray();
        for (Map.Entry<String,String> entry : name.entrySet()){
            String key = entry.getKey();
            String value = entry.getValue();
            JSONObject result = new JSONObject();
            result.put("PROVINCE_NAME",key);
            result.put("PROVINCE_CODE",code.get(key));
            result.put("ORDER_INFO",mm.get(key));
            resultList.add(result);
        }
        return  resultList;
    }


//    //解析订单解析的结果
//    public List<Map<String,Object>> dnsTaskPase(JSONObject results){
//        List<Map<String,Object>> resultList = null;
//        try{
//            resultList = new ArrayList<>();
//            Map<String,Object> areaMap = domainDao.queryAreaMap();
//            JSONArray queryTasks = results.getJSONArray("queryTask");
//            if (queryTasks == null) {
//                return null;
//            }
//            Map<String,Object> resultMap = new HashMap<>();
//            for (int i=0;i<queryTasks.size();i++){
//                JSONObject task = queryTasks.getJSONObject(i);
//                String dateTime = task.getString("dateTime");
//                String domainName = task.getString("domain");
//                JSONArray records = task.getJSONArray("record");
//                if (records != null){
//                    for (int l=0;l<records.size();l++){
//                        JSONObject record = records.getJSONObject(l);
//                        JSONArray ress = record.getJSONArray("res");
//                        String type = record.getString("type");
//                        for (int j = 0; j < ress.size();j++){
//                            resultMap = new HashMap<>();
//                            JSONObject res = ress.getJSONObject(j);
//                            String province =  res.getString("province");
//                            String provinceName = (String)areaMap.get(province);
//                            resultMap.put("PROVINCE_CODE",province);
//                            resultMap.put("dateTime",dateTime);
//                            resultMap.put("PROVINCE_NAME",provinceName);
//                            List<Map<String,Object>> areaList = new ArrayList<>();
//                            if (res.containsKey("area")){
//                                Map<String,Object> domainMap = new HashMap<>();
//                                Object aaa = res.get("area");
//                                if (aaa instanceof JSONArray){
//                                    JSONArray areas = res.getJSONArray("area");
//                                    for (int k=0;k<areas.size();k++){
//                                        domainMap = new HashMap<>();
//                                        JSONObject area = areas.getJSONObject(k);
//                                        String info = area.getString("info");
//                                        String areaCode = area.getString("areaCode");
//                                        String areaName = (String)areaMap.get(province);
//                                        domainMap.put("DOMAIN_NAME",domainName);
//                                        domainMap.put("RES",info);
//                                        domainMap.put("TYPE",type);
//                                        domainMap.put("AREA_NAME",areaName);
//                                        domainMap.put("AREA_CODE",areaCode);
//                                        areaList.add(domainMap);
//                                    }
//                                }else{
//                                    JSONObject area = res.getJSONObject("area");
//                                    String info = area.getString("info");
//                                    String areaCode = area.getString("areaCode");
//                                    String areaName = (String)areaMap.get(province);
//                                    domainMap.put("DOMAIN_NAME",domainName);
//                                    domainMap.put("RES",info);
//                                    domainMap.put("TYPE",type);
//                                    domainMap.put("AREA_NAME",areaName);
//                                    domainMap.put("AREA_CODE",areaCode);
//                                    areaList.add(domainMap);
//                                }
//                            }
//                            resultMap.put("ORDER_INFO",areaList);
//                            resultList.add(resultMap);
//                        }
//                    }
//                }
//            }
//        }catch (Exception e){
//            throw e;
//        }
//        return resultList;
//    }










































}
